import {uSelectDevReportDataByQueryVo, selectDevReportTypeApi} from '@/api/alarm'
import {CCard} from '@/components/card'
import {IconImg, ParamOfStatus} from '@/components/image'
import {DeviceSelect} from '@/components/select/device'
import {ParamSelect} from '@/components/select/param'
import {CnBoldP, CnBoldSpan, CnMediumSpan, CnNormalP, CnNormalSpan} from '@/components/text'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {getUserId} from '@/libs/auth'
import {time2str} from '@/libs/date'
import dayjs, {Dayjs} from 'dayjs'
import {toAlarmConfig} from '@/libs/pageRedirect'

type TableColumn = CColumn<Alarm.TableData>

export default defineComponent({
  name: 'alarmManagement',
  setup() {
    const {store} = useGlobalAPI()

    const state = reactive<{
      tableDatas: Alarm.TableData[]
      tableTotal: number
      currentDevId: number | undefined
      currentParamCode: string | undefined
      dateRange: ['', '']
      pagation: Paging
      tableLoading: boolean
    }>({
      currentDevId: undefined,
      currentParamCode: undefined,
      dateRange: ['', ''],
      tableDatas: [],
      tableTotal: 0,
      pagation: {
        page: 1,
        size: 15
      },
      tableLoading: false
    })

    const columns: TableColumn[] = [
      {
        title: '设备',
        dataIndex: 'devName'
      },
      {
        title: '内容',
        dataIndex: 'devReportContent',
        customRender({record, text}) {
          return <ParamOfStatus status={record.paramStatus}>{text}</ParamOfStatus>
        }
      },
      {
        title: '时间',
        dataIndex: 'devReportTime',
        customRender({text}) {
          let value = time2str(text)
          return value
        }
      }
    ]

    interface reportType {
      id: number
      sort: number
      status: string
      dictName: string
      dictDesc: string
      dictCode: string
      dictTypeCode: string
      dictValue: string
      createTime: string
    }

    type reportTypeListType = reportType[]

    // 保存报警类型的数据
    const reportTypeList = ref<reportTypeListType>([])

    // 当前类型Code
    const currentReportTypeDictCode = ref('')

    // 查询报警类型的函数
    const selectDevReportTypeFunc = async () => {
      const res = await selectDevReportTypeApi()
      reportTypeList.value = res.data
      console.log(reportTypeList.value)
    }

    onMounted(() => {
      selectDevReportTypeFunc()
      // const userId = getUserId()
      // if (!userId) return
      // state.tableLoading = true
      // const startTime = state.dateRange[0]
      // const endTime = state.dateRange[1]
      // uSelectDevReportDataByQueryVo({
      //   userId,
      //   devId: state.currentDevId,
      //   startTime,
      //   endTime,
      //   page: state.pagation.page,
      //   size: state.pagation.size,
      //   paramCode: state.currentParamCode
      // })
      //   .then(res => {
      //     state.tableDatas = res.data.list
      //     state.tableTotal = res.data.total
      //     nextTick(() => {
      //       store.dispatch('layoutMain/MAINSCROLLTOTOP')
      //     })
      //     state.tableLoading = false
      //   })
      //   .catch(err => {
      //     state.tableLoading = false
      //   })
    })

    function getTableData() {
      const userId = getUserId()
      if (!userId) return
      state.tableLoading = true
      const startTime = state.dateRange[0] == '' ? '' : state.dateRange[0] + ' 00:00:00'
      const endTime = state.dateRange[1] == '' ? '' : state.dateRange[1] + ' 23:59:59'
      uSelectDevReportDataByQueryVo({
        userId,
        devId: state.currentDevId,
        startTime,
        endTime,
        page: state.pagation.page,
        size: state.pagation.size,
        paramCode: state.currentParamCode,
        devReportType: currentReportTypeDictCode.value
      })
        .then(res => {
          state.tableDatas = res.data.list
          state.tableTotal = res.data.total
          nextTick(() => {
            store.dispatch('layoutMain/MAINSCROLLTOTOP')
          })
          state.tableLoading = false
        })
        .catch(err => {
          state.tableLoading = false
        })
    }

    function resetSearchLine() {
      state.currentDevId = undefined
      state.currentParamCode = undefined
      state.dateRange = ['', '']
    }

    watch(
      () => state.currentDevId,
      n => {
        getTableData()
      }
    )

    watch(
      () => state.currentParamCode,
      n => {
        getTableData()
      }
    )

    watch(
      () => state.dateRange,
      n => {
        getTableData()
      },
      {deep: true}
    )

    watch(
      () => state.pagation,
      n => {
        getTableData()
      },
      {deep: true}
    )

    watch(
      () => currentReportTypeDictCode.value,
      n => {
        getTableData()
      },
      {deep: true}
    )

    onMounted(() => {
      getTableData()
    })

    // 计算报警类型的颜色类名的函数
    const compAlamColorClassFunc = () => {
      let strClass = ''
      switch (currentReportTypeDictCode.value) {
        case '0173':
          strClass = 'cSelectedRed'
          break

        case '0174':
          strClass = 'cSelectedOrange'
          break

        case '0175':
          strClass = 'cSelectedGray'
          break
        default:
          break
      }

      return strClass
    }

    return () => (
      <div class=''>
        <CnBoldP class='mt-11 text-20'>报警管理</CnBoldP>
        <CnNormalP class='mt-6 text-4xText'>根据您设置的报警标准，将设备检测情况汇报给您</CnNormalP>
        <CCard class='mt-20 bg-white' title='报警信息' canHoverMove={false}>
          <div class='mt-16 inline-grid grid-cols-5 gap-x-16 mb-19'>
            <span style='line-height:28px'>
              <CnBoldSpan>报警类型：</CnBoldSpan>
            </span>
            {/* <CnBoldSpan>报警类型：</CnBoldSpan>
            <CnNormalSpan>设备在线</CnNormalSpan>
            <CnNormalSpan>设备离线</CnNormalSpan>
            <CnNormalSpan>水质</CnNormalSpan> */}
            <a-button
              size='small'
              class={[
                'flex item-center justify-center shadow-none p-0 h-auto',
                currentReportTypeDictCode.value == '' ? 'cSelected' : ''
              ]}
              onClick={() => {
                currentReportTypeDictCode.value = ''
              }}
            >
              <CnNormalSpan
                class={[
                  'cursor-pointer rounded-2 px-6 py-4',
                  currentReportTypeDictCode.value == '' ? 'colorWhite' : ''
                ]}
              >
                所有类型
              </CnNormalSpan>
            </a-button>
            {reportTypeList.value.map(item => (
              <a-button
                size='small'
                class={[
                  'flex item-center justify-center shadow-none p-0 h-auto',
                  currentReportTypeDictCode.value == item.dictCode ? compAlamColorClassFunc() : ''
                ]}
                onClick={() => {
                  currentReportTypeDictCode.value = item.dictCode
                }}
              >
                <CnNormalSpan
                  class={[
                    'cursor-pointer rounded-2   py-4 w-70',
                    currentReportTypeDictCode.value == item.dictCode ? 'colorWhite' : ''
                  ]}
                >
                  {item.dictName}
                  {/* 所有类型 */}
                </CnNormalSpan>
              </a-button>
            ))}
          </div>
          <div class='flex items-center mb-19'>
            <CnBoldSpan class='inline-flex  items-center mr-16'>选择设备：</CnBoldSpan>
            <DeviceSelect
              class='inline-block'
              v-model={[state.currentDevId, 'value']}
            ></DeviceSelect>
          </div>

          {state.currentDevId ? (
            <div class='flex items-center mb-19'>
              <CnBoldSpan class='inline-flex items-center mr-16'>选择参数：</CnBoldSpan>
              <ParamSelect
                v-model={[state.currentParamCode, 'value']}
                devId={state.currentDevId}
                lazy={false}
              ></ParamSelect>
            </div>
          ) : null}

          <div class='flex items-center'>
            <CnBoldSpan class='mr-16'>时间范围：</CnBoldSpan>

            <a-range-picker
              class='mr-16'
              v-model={[state.dateRange, 'value']}
              allowClear={false}
              valueFormat='YYYY MM DD'
            ></a-range-picker>

            <div class='inline-grid grid-cols-3 gap-x-16'>
              <a-button class='bg-primary'>
                <div class='flex items-center'>
                  <IconImg class='w-16 h-16 mr-8' imgName='magnifying-glass'></IconImg>
                  <CnNormalSpan class='text-white' onClick={getTableData}>
                    查询
                  </CnNormalSpan>
                </div>
              </a-button>
              <a-button class='bg-info'>
                <CnNormalSpan class='text-white' onClick={() => resetSearchLine()}>
                  重置
                </CnNormalSpan>
              </a-button>
              {/* <a-button
                class='bg-redirectBtn'
                onClick={() => {
                  toAlarmConfig()
                }}
              >
                <CnNormalSpan>报警配置</CnNormalSpan>
              </a-button> */}
            </div>
          </div>
          {/* <SplitLine class='mx-16'></SplitLine> */}

          <a-table
            class='mt-20'
            id='alarmTable'
            loading={state.tableLoading}
            columns={columns}
            dataSource={state.tableDatas}
            pagination={{
              current: state.pagation.page,
              pageSize: state.pagation.size,
              size: 'small',
              total: state.tableTotal,
              showTotal: (total: number) => `共 ${total} 条`,
              onChange: (page: number, size: number) => {
                console.log(page, size)
                state.pagation = {
                  page: page,
                  size: size
                }
              }
            }}
          ></a-table>
        </CCard>
      </div>
    )
  }
})
